/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mindorks.demo.slice;

import com.mindorks.demo.ResourceTable;
import com.mindorks.demo.bean.NavigationDataBean;
import com.mindorks.demo.provider.NavigationProvider;
import com.mindorks.placeholderview.LoadImageInstance;
import com.mindorks.placeholderview.Utils;
import com.mindorks.placeholderview.bean.ImageBean;
import com.squareup.picasso.Picasso;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.window.dialog.ToastDialog;
import ohos.multimodalinput.event.TouchEvent;

import java.util.ArrayList;
import java.util.List;

/**
 * PhotosAbilitySlice
 *
 * @since 2021-05-27
 */
public class PhotosAbilitySlice extends AbilitySlice implements Component.ClickedListener,
        Animator.StateChangedListener {
    /**
     * 抽屉动画的执行时长
     */
    private static final long TIMER_DRAWER_ANIMATOR = 200;

    private ListContainer mColumnListContainer;
    private DirectionalLayout mImagesLayout;
    private LoadImageInstance mLoadImageInstance;
    private Image mImage;
    private DirectionalLayout mNavigationLayout;
    private Component mMaskingLayout;
    private AnimatorProperty mAnimatorLayout;
    private ListContainer mNavigationLC;
    private List<ImageBean> mImageBeanList = new ArrayList<>();
    private List<NavigationDataBean> mNavigationData = new ArrayList<>();
    private DirectionalLayout mColumnImagesLayout;
    private DirectionalLayout mNavTitleLayout;
    private float mTouchStartX;
    private float mContentPositionX;
    private float mContentPositionY;
    private float mMoveX;
    private ScrollView mScrollLayout;
    private AnimatorValue mAnimatorValue;
    private float mLayoutMoveX;
    private int mAnimatorEndFlag = -1;
//    private DisplayImageOptions mOptions;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_photo);

        initData();
        initView();
        initListener();
    }

    private void initData() {
        mLoadImageInstance = LoadImageInstance.getInstance(this);
        mImageBeanList = Utils.loadImages(this);
        mNavigationData = getNavigationData();
    }

    private void initView() {
        mScrollLayout = (ScrollView) findComponentById(ResourceTable.Id_scroll_layout);
        mMaskingLayout = findComponentById(ResourceTable.Id_masking_layout);
        mNavigationLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_main_drawer_layout);
        mImage = (Image) findComponentById(ResourceTable.Id_menu_image);
        mNavTitleLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_navigation_title);
        mNavigationLC = (ListContainer) findComponentById(ResourceTable.Id_navigation_list_container);
        NavigationProvider navigationProvider = new NavigationProvider(this, mNavigationData);
        mNavigationLC.setItemProvider(navigationProvider);

        mImagesLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_row_images_layout);

        mColumnImagesLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_column_image_layout);
        for (int i = 0; i < mImageBeanList.size(); i++) {
            Image image = new Image(this);
            image.setScaleMode(Image.ScaleMode.STRETCH);
            image.setLayoutConfig(new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT,
                    500));
            // 使用本地图片
//            image.setPixelMap(imageBeanList.get(i).getMediaId());

            // 使用第三方框架请求图片
//            ImageLoader.getInstance().displayImage(mImageBeanList.get(i).getUrl(), image, mOptions, null);
            Picasso.get()
                    .load(mImageBeanList.get(i).getUrl())
                    .fit()
                    .tag(this)
                    .into(image);

            // 使用自定义的网络请求图片
//            WeakReference<Image> imageWeakReference = new WeakReference<Image>(image);
//            mLoadImageInstance.loadImageFromUrlAsync(imageWeakReference, mImageBeanList.get(i).getUrl());
            if (i != mImageBeanList.size() - 1) {
                image.setMarginBottom(20);
            }
            ShapeElement shapeElement = new ShapeElement();
            shapeElement.setCornerRadiiArray(new float[]{20, 20, 20, 20, 20, 20, 20, 20});
            shapeElement.setShape(ShapeElement.RECTANGLE);
            shapeElement.setStroke(5, new RgbColor(211, 211, 211));
            image.setBackground(shapeElement);
            mColumnImagesLayout.addComponent(image);
        }

        if (mImageBeanList.size() >= 15) {
            for (int i = 5; i < 15; i++) {
                Image image = new Image(this);
                image.setScaleMode(Image.ScaleMode.STRETCH);
                image.setLayoutConfig(new ComponentContainer.LayoutConfig(300, 300));

                // 使用本地图片
//            image.setPixelMap(imageBeanList.get(i).getMediaId());

                // 使用第三方框架请求图片
//                ImageLoader.getInstance().displayImage(mImageBeanList.get(i).getUrl(), image, mOptions, null);
                Picasso.get()
                        .load(mImageBeanList.get(i).getUrl())
                        .fit()
                        .tag(this)
                        .into(image);

                // 使用自定义的网络请求图片
//                WeakReference<Image> imageWeakReference = new WeakReference<Image>(image);
//                mLoadImageInstance.loadImageFromUrlAsync(imageWeakReference, mImageBeanList.get(i).getUrl());
                if (i != mImageBeanList.size() - 1) {
                    image.setMarginRight(20);
                }
                ShapeElement shapeElement = new ShapeElement();
                shapeElement.setCornerRadiiArray(new float[]{20, 20, 20, 20, 20, 20, 20, 20});
                shapeElement.setShape(ShapeElement.RECTANGLE);
                shapeElement.setStroke(5, new RgbColor(211, 211, 211));
                image.setBackground(shapeElement);
                mImagesLayout.addComponent(image);
            }
        }
    }

    private void initListener() {
        mMaskingLayout.setClickedListener(this);
        mMaskingLayout.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                switch (touchEvent.getAction()) {
                    case TouchEvent.PRIMARY_POINT_UP:
                        executeAnimation(1);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
        mImage.setClickedListener(this);
        mNavTitleLayout.setClickedListener(component -> {
        });
        mNavigationLayout.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                switch (touchEvent.getAction()) {
                    case TouchEvent.PRIMARY_POINT_DOWN:
                        mScrollLayout.setEnabled(false);
                        mTouchStartX = touchEvent.getPointerScreenPosition(0).getX();
                        mContentPositionX = component.getContentPositionX();
                        mContentPositionY = component.getContentPositionY();
                        break;
                    case TouchEvent.POINT_MOVE:
                        if (mMaskingLayout.getVisibility() == Component.HIDE) {
                            mMaskingLayout.setVisibility(Component.VISIBLE);
                        }
                        mMoveX = touchEvent.getPointerScreenPosition(0).getX() - mTouchStartX;
                        if (mContentPositionX + mMoveX < -700 && mLayoutMoveX > -700) {
                            component.setContentPosition(-700, (int) mContentPositionY);
                            mMaskingLayout.setAlpha(0);
                            break;
                        }
                        if (mContentPositionX + mMoveX > 0 && mLayoutMoveX < 0) {
                            component.setContentPosition(0, (int) mContentPositionY);
                            mMaskingLayout.setAlpha(0.5f);
                            break;
                        }
                        mLayoutMoveX = mContentPositionX + mMoveX;
                        System.out.println("PhotosAbilitySlice--" + mLayoutMoveX + "**" + mContentPositionX + "**" + mMoveX);
                        if (mLayoutMoveX <= 0 && mLayoutMoveX >= -700) {
                            component.setContentPosition((int) mLayoutMoveX, (int) mContentPositionY);
                            mMaskingLayout.setAlpha((1 + mLayoutMoveX / 700) / 2);
                        }
                        break;
                    case TouchEvent.PRIMARY_POINT_UP:
                        System.out.println("PhotosAbilitySlice--PRIMARY_POINT_UP" + (mContentPositionX + mMoveX)+"--"+mMoveX);
                        float upX = mContentPositionX + mMoveX;
                        if (upX <= 0 && upX > -700) {
                            mAnimatorLayout = component.createAnimatorProperty();

                            mAnimatorValue = new AnimatorValue();
                            mAnimatorValue.setDuration(TIMER_DRAWER_ANIMATOR);
                            mAnimatorValue.setValueUpdateListener((animatorValue, v) -> {
                                if (upX > -350 && mMoveX > 0) {
                                    mMaskingLayout.setAlpha((1 + upX * (1 - v) / 700) / 2);
                                    mAnimatorEndFlag = 0;
                                } else if (upX <= -350 && mMoveX > 0) {
                                    mMaskingLayout.setAlpha((1 + (upX + (-700 - upX) * v) / 700) / 2);
                                    mAnimatorEndFlag = 1;
                                } else if (upX > -100 && mMoveX <= 0){
                                    mMaskingLayout.setAlpha((1 + upX * (1 - v) / 700) / 2);
                                    mAnimatorEndFlag = 0;
                                } else if (upX <= -100 && mMoveX <= 0){
                                    mMaskingLayout.setAlpha((1 + (upX + (-700 - upX) * v) / 700) / 2);
                                    mAnimatorEndFlag = 1;
                                }
                            });
                            mAnimatorValue.setStateChangedListener(PhotosAbilitySlice.this);
                            mAnimatorValue.start();
                            if (upX > -350 && mMoveX > 0) {
                                mAnimatorLayout.moveFromX(upX).moveToX(0).setDuration(TIMER_DRAWER_ANIMATOR);
                            } else if (upX <= -350 && mMoveX > 0){
                                mAnimatorLayout.moveFromX(upX).moveToX(-700).setDuration(TIMER_DRAWER_ANIMATOR);
                            } else if (upX > -100 && mMoveX <= 0){
                                mAnimatorLayout.moveFromX(upX).moveToX(0).setDuration(TIMER_DRAWER_ANIMATOR);
                            } else if (upX <= -100 && mMoveX <= 0){
                                mAnimatorLayout.moveFromX(upX).moveToX(-700).setDuration(TIMER_DRAWER_ANIMATOR);
                            }
                            mAnimatorLayout.start();
                        }
                        mScrollLayout.setEnabled(true);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });

        mNavigationLC.setItemClickedListener((listContainer, component, i, l) -> {
//            new ToastDialog(this).setText(mNavigationData.get(i).getName()).show();
            DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(this)
                    .parse(ResourceTable.Layout_toast_layout, null, false);
            ((Text)toastLayout.findComponentById(ResourceTable.Id_msg_toast)).setText(mNavigationData.get(i).getName());
            new ToastDialog(getContext())
                    .setContentCustomComponent(toastLayout)
                    .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                    .setTransparent(true)
                    .show();
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_menu_image:
                executeAnimation(0);
                break;
            case ResourceTable.Id_masking_layout:
                executeAnimation(1);
                break;
            default:
                break;
        }
    }

    private List<NavigationDataBean> getNavigationData() {
        List<NavigationDataBean> dataBeanList = new ArrayList<>();
        dataBeanList.add(new NavigationDataBean("Profile", ResourceTable.Media_ic_account_circle_black));
        dataBeanList.add(new NavigationDataBean("Requests", ResourceTable.Media_ic_compare_arrows_black));
        dataBeanList.add(new NavigationDataBean("Groups", ResourceTable.Media_ic_group_work_black));
        dataBeanList.add(new NavigationDataBean("Messages", ResourceTable.Media_ic_email_black));
        dataBeanList.add(new NavigationDataBean("Notifications", ResourceTable.Media_ic_notifications_black));
        dataBeanList.add(new NavigationDataBean("Settings", ResourceTable.Media_ic_settings_black));
        dataBeanList.add(new NavigationDataBean("Terms", ResourceTable.Media_ic_book_black));
        dataBeanList.add(new NavigationDataBean("Logout", ResourceTable.Media_ic_exit_to_app_black));
        return dataBeanList;
    }

    @Override
    public void onStart(Animator animator) {

    }

    @Override
    public void onStop(Animator animator) {

    }

    @Override
    public void onCancel(Animator animator) {

    }

    @Override
    public void onEnd(Animator animator) {
        System.out.println("PhotosAbilitySlice.Animator.onEnd");
        if (mAnimatorEndFlag == 1) {
            mMaskingLayout.setVisibility(Component.HIDE);
        }
    }

    @Override
    public void onPause(Animator animator) {

    }

    @Override
    public void onResume(Animator animator) {

    }

    /**
     * 选择要执行的动画
     *
     * @param whichAni
     */
    private void executeAnimation(int whichAni) {
        mAnimatorValue = new AnimatorValue();
        mAnimatorValue.setDuration(TIMER_DRAWER_ANIMATOR);

        if (whichAni == 0) {

            System.out.println("PhotosAbilitySlice.Id_menu_image" + mNavigationLayout.getContentPositionX());
            if (mNavigationLayout.getContentPositionX() < (-700 + 50)) {
                System.out.println("PhotosAbilitySlice.Id_menu_image------" + mNavigationLayout.getContentPositionX() + "--" + mAnimatorValue);
                mAnimatorValue.setValueUpdateListener((animatorValue, v) -> {
                    System.out.println("PhotosAbilitySlice.Id_menu_image.mAnimatorValue------" + v);
                    mNavigationLayout.setContentPosition((int) (-700 * (1 - v)), (int) mNavigationLayout.getContentPositionY());
                    mMaskingLayout.setVisibility(Component.VISIBLE);
                    mMaskingLayout.setAlpha(v / 2);
                    mAnimatorEndFlag = 0;
                });
            }
        } else if (whichAni == 1) {
            System.out.println("PhotosAbilitySlice.Id_masking_layout");
            if (mNavigationLayout.getContentPositionX() > -50) {
                mAnimatorValue.setValueUpdateListener((animatorValue, v) -> {
                    mNavigationLayout.setContentPosition((int) (-700 * v), (int) mNavigationLayout.getContentPositionY());
                    mMaskingLayout.setAlpha((1 - v) / 2);
                    mAnimatorEndFlag = 1;
                });
            }
        }
        mAnimatorValue.setStateChangedListener(PhotosAbilitySlice.this);
        mAnimatorValue.start();
    }
}
